import axios from 'axios'
import router from '@/router'

const service = axios.create({
  baseURL: 'http://localhost:8081',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
      console.log('Request with token:', token)
    }
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 如果是登录请求，保存token和用户信息
    if (response.config.url.includes('/api/user/login')) {
      const { token, user } = response.data
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      console.log('Saved user info:', user)
    }
    return response.data
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        // 清除失效的认证信息
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        router.push('/login')
      }
      return Promise.reject(error.response.data)
    }
    return Promise.reject(error)
  }
)

export default service 